package com.cqeec.bootdemo.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;
//拦截controller
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler({SQLIntegrityConstraintViolationException.class, DuplicateKeyException.class})
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException e){
//        获取异常信息
        log.error(e.getMessage());
        if(e.getMessage().contains("Duplicate entry")){
//            拿出错误的的用户名
            String[] split = e.getMessage().split(" ");
            String msg = split[2] + "已存在";
            return R.error(msg);
        }
        return R.error("未知错误");
    }

    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException e){
        // 输出日志
        log.error("出现了自定异常，异常为:{}",e.getMessage());
        return R.error(e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public R<String> exceptionHandler(Exception e){
        // 输出日志
        log.error("出现了自定异常，异常为:{}",e.getMessage());
        return R.error("服务器正忙，请稍后再试");
    }
}
